import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import federation from 'vite-federation';
import { fileURLToPath, URL } from "node:url";
import { visualizer } from 'rollup-plugin-visualizer';
import { reg, init } from 'vite-plugin-nacos';

export default defineConfig(async ({ mode }) => {
    const env = loadEnv(mode, process.cwd());
    const { VITE_MODEL_SHARED_URL } = await init(env)

    // console.log("VITE_MODEL_SHARED_URL: ", VITE_MODEL_SHARED_URL);

    return {
        plugins: [
            reg(),

            federation({
                name: env.VITE_SERVER_NAME,
                remotes: {
                    shared: `${VITE_MODEL_SHARED_URL}/${env.VITE_MODEL_SHARED_NAME}/assets/remoteEntry.js`
                },
                exposes: { // 暴露给主应用的资源（按功能分组）
                    './ProductDomain': './src/domains/product/index.ts', // 领域层（实体、服务、接口等）
                    './ProductRouter': './src/features/product/router/index.ts' // 商品路由
                },
                shared: {
                    vue: { import: false, generate: false, requiredVersion: '^3.5.18' },
                    'vue-router': { import: false, generate: false, requiredVersion: '^4.0.6' },
                    pinia: { import: false, generate: false, requiredVersion: '^3.0.3' },
                }
            }),
            vue(),
            vueJsx(),
            vueDevTools(),
            visualizer({
                title: "商品模块依赖分析",
                filename: 'dist/stats.html', // 分析文件输出路径
                open: false, // 构建完成后自动打开
                gzipSize: true, // 显示gzip后的大小
                brotliSize: true, // 显示brotli后的大小
            })
        ],
        build: {
            target: 'esnext',
            cssCodeSplit: true,
            rollupOptions: {
                // 关键配置：告诉 Rollup 不要处理模块联邦的导入
                external: ['shared/normalize'],
                output: {
                    minifyInternalExports: false
                }
            }
        },
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src/', import.meta.url)),
                '@shared': fileURLToPath(new URL('./src/shared/', import.meta.url)),
                '@features': fileURLToPath(new URL('./src/features/', import.meta.url)),
                '@domains': fileURLToPath(new URL('./src/domains/', import.meta.url))
            },
        },
    }
});